package com.bupt.ilink.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.ilink.entity.Studyspace.*;
import com.bupt.ilink.entity.Studyspace.DTO.CourseResponse;
import com.bupt.ilink.entity.Studyspace.tree.StudyTreeFavorite;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.mapper.*;
import com.bupt.ilink.service.*;
import com.bupt.ilink.service.impl.StudyaboutStudentServiceImpl;
import com.bupt.ilink.utils.R;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import org.checkerframework.checker.units.qual.A;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/StudySpaceStudent")
public class StudyaboutStudentController {
    private static final Logger logger = LoggerFactory.getLogger(StudyaboutStudentController.class);
    @Autowired
    private OssService ossService;

    @Autowired
    private StudyTeacherCourseMapper studyTeacherCourseMapper;

    @Autowired
    private StudyaboutTeacherService studyaboutTeacherService;

    @Autowired
    private StudyaboutStudentService studyaboutStudentService;

    @Autowired
    private StudyTeacherCoursesTeacherService studyTeacherCoursesTeacherService;

    @Autowired
    private StudyTeacherCoursesFavoriteService studyTeacherCoursesFavoriteService;

    @Autowired
    private StudyTeacherCoursesFavoriteMapper studyTeacherCoursesFavoriteMapper;

    @Autowired
    private StudyCourseFileMapper studyCourseFileMapper;

    @Autowired
    private StudyFileSourceMapper studyFileSourceMapper;

    @Autowired
    private CourseSourceMapper courseSourceMapper;

    @Autowired
    private StudyWebSourseMapper studyWebSourseMapper;

    @Autowired
    private StudyWebSourseService studyWebSourseService;

    @Autowired
    private FileTranscriptionService fileTranscriptionService;

    //课程-章节-小节
    //资源移动（到当前课程的其他小节）
    @PostMapping("/moveResourse")
    public R moveResourse(
            @RequestParam Long resourceId,
            @RequestParam String resourceType,
            @RequestParam String newPath,
            @RequestParam Long courseId){

        // 使用 newPath 查找新的文件夹 ID
        StudyCourseFile newFolder = studyCourseFileMapper.selectOne(
                new QueryWrapper<StudyCourseFile>().eq("file_path", newPath).eq("course_id", courseId)
        );
        if (newFolder == null) {
            return R.failure("无效目标路径");
        }

        switch (resourceType.toLowerCase()) {
            case "文档":
                return studyaboutStudentService.moveDocumentResource(resourceId, newFolder, courseId);
            case "音视频":
                return studyaboutStudentService.moveAudioVideoResource(resourceId, newFolder, courseId);
            case "网页":
                return studyaboutStudentService.moveWebResource(resourceId, newFolder, courseId);
            default:
                return R.failure("无效资源");
        }
    }

    /**
     * @author dzy
     * @return 最常使用的8个标签(List<String>形式)
     */
    @GetMapping("/getCommonCourseTags")
    public R getCommonCourseTags(){
        try {
            return R.ok(studyaboutTeacherService.getCommonTags());
        } catch(Exception e){
            return R.failure("内部服务器错误：" + e);
        }
    }

    //小节移动（到当前课程的其他章节）
    @PostMapping("/moveSection")
    @Transactional
    public R moveSection(
            @RequestParam Long sectionId,
            @RequestParam Long targetChapterId,
            @RequestParam Long courseId,
            @RequestParam(defaultValue = "0") int sortOrder) {

        // 获取当前小节和目标章节的信息
        StudyCourseFile sectionFolder = studyCourseFileMapper.selectById(sectionId);
        StudyCourseFile targetChapterFolder = studyCourseFileMapper.selectById(targetChapterId);

        if (sectionFolder == null || targetChapterFolder == null) {
            return R.failure("无效的章节或小节ID");
        }

        // 确保目标章节和小节在同一课程下
        if (!sectionFolder.getCourseId().equals(courseId) || !targetChapterFolder.getCourseId().equals(courseId)) {
            return R.failure("目标章节与小节不属于同一课程");
        }

        // 保存原始文件路径
        String originalSectionPath = sectionFolder.getFilePath();

        // 生成新的文件路径
        String newSectionPath = targetChapterFolder.getFilePath() + sectionFolder.getCourseFileId() + "/";

        // 处理OSS中文件夹的移动
        if (!ossService.moveDirectory(originalSectionPath, newSectionPath)) {
            logger.error("OSS文件夹移动失败");
            return R.failure("OSS文件夹移动失败");
        }

        // OSS移动成功后，进行MySQL事务
        try {
            // 更新小节的父文件夹ID和文件路径，以及排序
            sectionFolder.setParentId(targetChapterId);
            sectionFolder.setFilePath(newSectionPath);
            sectionFolder.setSortOrder(sortOrder+1);
            studyCourseFileMapper.updateById(sectionFolder);

            // 更新章节的子文件夹ID
            targetChapterFolder.setChildId(sectionId);
            studyCourseFileMapper.updateById(targetChapterFolder);

            // 更新小节中的所有资源的路径和FileId
            moveResourcesInSection(sectionId, sectionFolder, originalSectionPath, newSectionPath);
        } catch (Exception e) {
            // 如果MySQL操作失败，尝试回滚OSS操作
            ossService.moveDirectory(newSectionPath, originalSectionPath);
            logger.error("目录MySQL更新失败并回滚OSS操作", e);
            throw new RuntimeException("MySQL更新失败并回滚OSS操作", e);
        }

        return R.ok("小节移动成功");
    }


    private void moveResourcesInSection(Long sectionId, StudyCourseFile newFolder, String originalSectionPath, String newSectionPath) {
        // 移动文档资源
        List<StudyFileSource> documents = studyFileSourceMapper.selectList(new QueryWrapper<StudyFileSource>().eq("file_id", sectionId));
        for (StudyFileSource document : documents) {
            // 更新FileId和路径
            document.setFileId(newFolder.getCourseFileId());

            String originalFilePath = document.getFilesourcePath();
            String objectName = originalFilePath.substring(originalFilePath.lastIndexOf("/") + 1);
            originalFilePath = originalFilePath.substring(0, originalFilePath.lastIndexOf("/") + 1);
            String newFilePath = newFolder.getFilePath();
            document.setFilesourcePath(newFilePath+objectName);
            studyFileSourceMapper.updateById(document);
        }

        // 移动音视频资源
        List<CourseSource> audioVideoResources = courseSourceMapper.selectList(new QueryWrapper<CourseSource>().eq("file_id", sectionId));
        for (CourseSource resource : audioVideoResources) {
            // 更新FileId和路径
            resource.setFileId(newFolder.getCourseFileId());

            String originalFilePath = resource.getFilesourcePath();
            String objectName = originalFilePath.substring(originalFilePath.lastIndexOf("/") + 1);
            originalFilePath = originalFilePath.substring(0, originalFilePath.lastIndexOf("/") + 1);
            String newFilePath = newFolder.getFilePath();
            resource.setFilesourcePath(newFilePath+objectName);

            //只修改麻紫嫣数据库
            boolean tranMove;
            String taskId = resource.getTaskId();
            try {
                tranMove = fileTranscriptionService.modifyFileTransInfoPath(taskId, newFolder.getFilePath());
            } catch (Exception e) {
                logger.error("转写 音视频资源文件移动失败", e);
                throw new RuntimeException("转写 音视频资源文件移动失败", e);
            }

            if (!tranMove) {
                logger.error("转写 音视频资源文件移动失败");
                throw new RuntimeException("转写 音视频资源文件移动失败");
            }
            courseSourceMapper.updateById(resource);
        }

        // 移动网页资源
        List<StudyWebSourse> webResources = studyWebSourseMapper.selectList(new QueryWrapper<StudyWebSourse>().eq("file_id", sectionId));
        for (StudyWebSourse webResource : webResources) {
            // 更新FileId和路径
            webResource.setFileId(newFolder.getCourseFileId());
//            webResource.setWebSoursePath(webResource.getWebSoursePath().replace(originalSectionPath, newSectionPath));
            studyWebSourseMapper.updateById(webResource);
        }

        // 递归处理子文件夹（如果有）
        List<StudyCourseFile> subFolders = studyCourseFileMapper.selectList(new QueryWrapper<StudyCourseFile>().eq("parent_id", sectionId));
        for (StudyCourseFile subFolder : subFolders) {
            String newSubFolderPath = newSectionPath + subFolder.getCourseFileId() + "/";
            subFolder.setFilePath(newSubFolderPath);
            studyCourseFileMapper.updateById(subFolder);

            // 递归移动子文件夹中的资源
            moveResourcesInSection(subFolder.getCourseFileId(), subFolder, originalSectionPath, newSubFolderPath);
        }
    }

    @PostMapping("/uploadWebSource")
    public R uploadWebSource(
            @RequestParam("courseFileId") Long courseFileId,
            @RequestParam("courseId") Long courseid,
            @RequestParam("web") String web,
            @RequestParam("webName") String webName){
        try{
            //雪花算法生成新的web_id
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);

            StudyCourseFile studyCourseFile = studyCourseFileMapper.selectById(courseFileId);
            if (studyCourseFile == null) {
                return R.failure("文件夹ID无效");
            }
            String filePath = studyCourseFile.getFilePath();

            StudyWebSourse webSourse = new StudyWebSourse();
            webSourse.setWebId(idGenerator.nextId());
            webSourse.setWebName(webName);
            webSourse.setFileId(courseFileId);
            webSourse.setWeb(web);
            webSourse.setCourseId(courseid);
            webSourse.setUploadedAt(new Date());
            studyWebSourseService.save(webSourse);

            return R.ok("上传网页成功"+webName);
        }catch (Exception e)
        {
            return R.failure("上传网页资源失败"+e);
        }
    }


    @GetMapping("/getSourceName")
    public R getSourceName(@RequestParam("sourceId") Long sourceId){
        StudyFileSource studyFileSource = studyFileSourceMapper.selectById(sourceId);
        if(studyFileSource != null){
            String name = studyFileSource.getFileName();
            return R.ok("文档资源找到名字"+name);
        }
        CourseSource courseSource = courseSourceMapper.selectById(sourceId);
        if(courseSource != null){
            String name = courseSource.getFileName();
            return R.ok("音视频资源找到名字"+name);
        }
        return R.failure("未找到该文件资源");
    }

    //  实现文件跳转
    @GetMapping("/getCourseFileUrl")
    public R getCourseFileUrl(@RequestParam("courseSourceId") Long filesourceId){
        String filesourcePath = "";
        StudyFileSource studyFileSource = studyFileSourceMapper.selectById(filesourceId);
        if(studyFileSource != null)
        {
            filesourcePath = studyFileSource.getFilesourcePath();
        }
        CourseSource studyMediaSource = courseSourceMapper.selectById(filesourceId);
        if(studyMediaSource != null){
            filesourcePath = studyMediaSource.getFilesourcePath();
        }
        if(Objects.equals(filesourcePath, "")){
            return R.failure("跳转文件未找到");
        }
        if(ossService.getFileUrl(filesourcePath) != null)
        {
            return R.ok(ossService.getFileUrl(filesourcePath));
        }
        return R.failure("OSS未找到该文件");
    }

    @GetMapping("/getCourseMetadata")
    public IPage<CourseResponse> getCourseMetadata(
            @AuthenticationPrincipal UserDetails userDetails,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String collection,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String tag,
            @RequestParam(defaultValue = "1") int page) {

        int size = 12;
        User user = (User) userDetails;
        String userId = user.getUserId();

        QueryWrapper<StudyTeacherCourse> queryWrapper = new QueryWrapper<>();

        // 处理“我收藏的”条件
        if ("我收藏的".equals(collection)) {
            List<Long> favoriteCourseIds = studyTeacherCoursesFavoriteService.list(
                    new QueryWrapper<StudyTeacherCoursesFavorite>().eq("user_id", userId)
            ).stream().map(StudyTeacherCoursesFavorite::getCourseId).collect(Collectors.toList());

            if (!favoriteCourseIds.isEmpty()) {
                queryWrapper.in("course_id", favoriteCourseIds);
            } else {
                // 如果用户没有收藏任何课程，返回空结果
                return new Page<>(page, size);
            }
        }

        // 处理 keyword 和 tag 的条件
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("course_name", keyword);
        }

        if (tag != null && !tag.isEmpty()) {
            queryWrapper.like("course_tag", tag);
        }

        // 处理排序条件
        if ("最热".equals(sortBy)) {
            queryWrapper.orderByDesc("view_num");
        } else if ("最新".equals(sortBy)) {
            queryWrapper.orderByDesc("created_at");
        }

        // 执行分页查询
        IPage<StudyTeacherCourse> studyTeacherCoursePage =
                studyaboutTeacherService.page(new Page<>(page, size), queryWrapper);

        // 将查询结果转换为 CourseResponse 对象
        List<CourseResponse> courseResponses = studyTeacherCoursePage.getRecords().stream()
                .map(course -> {
                    CourseResponse response = new CourseResponse();
                    response.setCourseId(course.getCourseId());
                    response.setTeacherId(course.getTeacherId());
                    response.setFolderId(course.getFolderId());
                    response.setCourseName(course.getCourseName());
                    response.setCourseTag(course.getCourseTag());
                    if(course.getCourseImage() != null)
                    {
                        response.setCourseImage(ossService.getFileUrl(course.getCourseImage()));
                    }else{
                        response.setCourseImage(null);
                    }
                    System.out.println("课程封面"+response.getCourseImage());
                    response.setCourseDescription(course.getCourseDescription());
                    response.setViewNum(course.getViewNum());
                    response.setCreatedAt(course.getCreatedAt());

                    // 设置教师信息
                    List<StudyTeacherCoursesTeacher> teachers = studyTeacherCoursesTeacherService.list(
                            new QueryWrapper<StudyTeacherCoursesTeacher>().eq("course_id", course.getCourseId())
                    );
                    response.setTeacher(teachers);

                    // 更新每个教师的teacherImage为OSS中的URL
                    teachers.forEach(teacher -> {
                        teacher.setTeacherImage(ossService.getFileUrl(teacher.getTeacherImage()));
                    });

                    return response;
                }).collect(Collectors.toList());

        // 返回分页结果
        Page<CourseResponse> courseResponsePage = new Page<>(page, size);
        courseResponsePage.setRecords(courseResponses);
        courseResponsePage.setTotal(studyTeacherCoursePage.getTotal());
        courseResponsePage.setCurrent(studyTeacherCoursePage.getCurrent());
        courseResponsePage.setSize(studyTeacherCoursePage.getSize());

        return courseResponsePage;
    }


    @GetMapping("/getCourseInformation")
    public CourseResponse getCourseInformation(@RequestParam("courseId") Long courseId){
        try {
            // 从数据库中查询课程信息
            StudyTeacherCourse studyTeacherCourse = studyTeacherCourseMapper.selectById(courseId);

            // 如果课程信息不存在，返回 null 或抛出异常
            if (studyTeacherCourse == null) {
//            throw new ResourceNotFoundException("Course not found with id: " + courseId);
                return null;
            }

            // 将 StudyTeacherCourse 转换为 CourseResponse
            CourseResponse response = new CourseResponse();
            response.setCourseId(studyTeacherCourse.getCourseId());
            response.setTeacherId(studyTeacherCourse.getTeacherId());
            response.setFolderId(studyTeacherCourse.getFolderId());
            response.setCourseName(studyTeacherCourse.getCourseName());
            response.setCourseTag(studyTeacherCourse.getCourseTag());
            response.setCourseDescription(studyTeacherCourse.getCourseDescription());
            response.setViewNum(studyTeacherCourse.getViewNum());
            response.setCreatedAt(studyTeacherCourse.getCreatedAt());
            response.setUpdatedAt(studyTeacherCourse.getUpdatedAt());

            // 设置课程图片 URL，如果存在
            if (studyTeacherCourse.getCourseImage() != null) {
                response.setCourseImage(ossService.getFileUrl(studyTeacherCourse.getCourseImage()));
            }

            // 查询并设置教师信息
            List<StudyTeacherCoursesTeacher> teachers = studyTeacherCoursesTeacherService.list(
                    new QueryWrapper<StudyTeacherCoursesTeacher>().eq("course_id", courseId)
            );

            // 更新每个教师的 teacherImage 为 OSS 中的 URL
            teachers.forEach(teacher -> {
                if (teacher.getTeacherImage() != null) {
                    teacher.setTeacherImage(ossService.getFileUrl(teacher.getTeacherImage()));
                }
            });

            response.setTeacher(teachers);

            return response;
        }catch (Exception e){
            logger.error("获取课程详细信息错误"+e.getMessage());
            return null;
        }
    }

    //  点击量
    @PostMapping("/addCourseViewNum")
    public R addCourseViewNum(@RequestParam String courseId){
        studyTeacherCourseMapper.incrementViewNum(courseId);
        return R.ok("点击量+1");
    }

    //  用户收藏
    @PostMapping("/addFavoriteCourse")
    public  R addFavoriteCourse(@AuthenticationPrincipal UserDetails userDetails,
                                @RequestParam String courseId){
        StudyTeacherCoursesFavorite favorite = new StudyTeacherCoursesFavorite();
        try{
            // 雪花算法生成的ID
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            Long favoriteId = idGenerator.nextId();

            User user = (User) userDetails;
            String userId = user.getUserId();

            Long count = studyTeacherCoursesFavoriteMapper.selectCount(
                    new LambdaQueryWrapper<StudyTeacherCoursesFavorite>()
                            .eq(StudyTeacherCoursesFavorite::getUserId, userId)
                            .eq(StudyTeacherCoursesFavorite::getCourseId, courseId)
            );

            // 如果已存在则不插入，直接返回 false 表示未插入
            if (count > 0) {
                logger.warn("User '{}' 已收藏 courseId '{}'，跳过插入", userId, courseId);
                return R.failure(userId+"userId已收藏courseId，跳过插入"+courseId);
            }

            favorite.setFavoriteId(favoriteId);
            favorite.setUserId(userId);
            favorite.setCourseId(Long.valueOf(courseId));

            studyTeacherCoursesFavoriteService.save(favorite);

            return R.ok("用户已经该课程新增至收藏夹");
        } catch (Exception e){
            return R.failure(e);
        }
    }

    @GetMapping("/list_favorite")
    public R getFavoriteList(@AuthenticationPrincipal UserDetails userDetails) {
        try{
            User user = (User) userDetails;
            String userId = user.getUserId();

            List<StudyTeacherCoursesFavorite> favoriteList = studyTeacherCoursesFavoriteService.getFavoriteListByUserId(userId);
            if(favoriteList != null){
                return R.ok(user.getUsername()+"用户的列表",favoriteList);
            }
            return R.failure("用户未收藏课程");
        }catch (Exception e){
            return R.failure("获取用户的收藏列表错误"+e.getMessage());
        }
    }

    @GetMapping("/list_favorite_course")
    public R getFavoriteCourseList(@AuthenticationPrincipal UserDetails userDetails) {
        try {
            User user = (User) userDetails;
            String userId = user.getUserId();

            // 获取用户收藏的课程列表
            List<StudyTeacherCoursesFavorite> favoriteList = studyTeacherCoursesFavoriteService.getFavoriteListByUserId(userId);

            if (favoriteList == null || favoriteList.isEmpty()) {
                return R.failure("用户未收藏课程");
            }

            // 获取每个课程的详细信息
            List<CourseResponse> courseResponses = new ArrayList<>();

            for (StudyTeacherCoursesFavorite favorite : favoriteList) {
                Long courseId = favorite.getCourseId();

                // 查询课程信息
                StudyTeacherCourse studyTeacherCourse = studyTeacherCourseMapper.selectById(courseId);

                if (studyTeacherCourse != null) {
                    CourseResponse response = new CourseResponse();
                    response.setCourseId(studyTeacherCourse.getCourseId());
                    response.setTeacherId(studyTeacherCourse.getTeacherId());
                    response.setFolderId(studyTeacherCourse.getFolderId());
                    response.setCourseName(studyTeacherCourse.getCourseName());
                    response.setCourseTag(studyTeacherCourse.getCourseTag());
                    response.setCourseDescription(studyTeacherCourse.getCourseDescription());
                    response.setViewNum(studyTeacherCourse.getViewNum());
                    response.setCreatedAt(studyTeacherCourse.getCreatedAt());

                    if (studyTeacherCourse.getCourseImage() != null) {
                        response.setCourseImage(ossService.getFileUrl(studyTeacherCourse.getCourseImage()));
                    }

                    // 查询并设置教师信息
                    List<StudyTeacherCoursesTeacher> teachers = studyTeacherCoursesTeacherService.list(
                            new QueryWrapper<StudyTeacherCoursesTeacher>().eq("course_id", courseId)
                    );

                    teachers.forEach(teacher -> {
                        if (teacher.getTeacherImage() != null) {
                            teacher.setTeacherImage(ossService.getFileUrl(teacher.getTeacherImage()));
                        }
                    });

                    response.setTeacher(teachers);
                    courseResponses.add(response);
                }
            }

            return R.ok(user.getUsername()+"用户的收藏课程信息", courseResponses);

        } catch (Exception e) {
            logger.error("获取收藏课程详细信息时出错: " + e.getMessage(), e);
            return R.failure("获取收藏课程详细信息出错: " + e.getMessage());
        }
    }

}
